import React, { useState, useEffect, useRef } from 'react';
import { Card, Spin, Input, Empty, Image, Typography } from 'antd';
import { CalendarOutlined, SearchOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { getDynamicPage, DynamicInfo } from '@/services/DynamicService';
import { famousPersonId } from '@/services';
import { FileDetail } from '@/services/index';
import styles from './index.less';
import dayjs from 'dayjs';
import InfiniteScroll from 'react-infinite-scroll-component';

const { Search } = Input;
const { Text } = Typography;

const DynamicPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<DynamicInfo[]>([]);
  // const [keyword, setKeyword] = useState('');
  const [hasMore, setHasMore] = useState(true);
  const [total, setTotal] = useState(0);
  const pageRef = useRef(1);
  const PAGE_SIZE = 10;

  

  const loadData = async (isRefresh = false, keyword = '') => {
    if (loading) return;
    try {
      setLoading(true);
      const currentPage = isRefresh ? 1 : pageRef.current;
      const response = await getDynamicPage({
        pageCurrent: currentPage,
        pageSize: PAGE_SIZE,
        status: 1,
        famousPersonId,
        keyword: keyword,
      });

      if (isRefresh) {
        setData(response.list);
        window.scrollTo(0, 0);
      } else {
        setData(prev => [...prev, ...response.list]);
      }

      setTotal(response.totalCount);
      setHasMore(currentPage * PAGE_SIZE < response.totalCount);

      if (!isRefresh) {
        pageRef.current += 1;
      } else {
        pageRef.current = 2;
      }
    } catch (error) {
      console.error('获取动态列表失败：', error);
    } finally {
      setLoading(false);
    }
  };

  // 初始加载数据
  useEffect(() => {
    loadData(true);
  }, []);

  const handleSearch = (value: string) => {
    loadData(true, value);
  };

  const handleDynamicClick = (id: number) => {
    history.push(`/dynamic/${btoa(id.toString())}`);
  };

  const renderMediaGrid = (imageList: FileDetail[] = []) => {
    if (!imageList?.length) return null;

    const getLayoutClass = (total: number) => {
      switch (total) {
        case 1: return styles.singleMedia;
        case 2: return styles.doubleMedia;
        case 3: return styles.tripleMedia;
        case 4: return styles.quadMedia;
        default: return styles.multiMedia;
      }
    };

    const displayCount = Math.min(imageList.length, 9);

    return (
      <div
        className={`${styles.mediaGrid} ${getLayoutClass(displayCount)}`}
        onClick={(e) => e.stopPropagation()}
      >
        <Image.PreviewGroup>
          {imageList.slice(0, displayCount).map((image, index) => (
            <div key={image.id} className={styles.mediaWrapper}>
              <div className={styles.imageItem}>
                <Image
                  src={`/api/file/play/${image.id}`}
                  alt=""
                />
                {index === displayCount - 1 && imageList.length > displayCount && (
                  <div className={styles.moreOverlay}>
                    +{imageList.length - displayCount}
                  </div>
                )}
              </div>
            </div>
          ))}
        </Image.PreviewGroup>
      </div>
    );
  };

  const formatDate = (timestamp: string) => {
    return dayjs(parseInt(timestamp)).format('YYYY-MM-DD HH:mm');
  };

  return (
    <div className={styles.container}>
      <div className={styles.searchBar}>
        <Search
          placeholder="搜索动态/标题/内容关键字"
          allowClear
          enterButton
          size="large"
          onSearch={handleSearch}
        />
        <div className={styles.searchInfo}>
          <Text type="secondary">
            {`找到 ${total} 条相关动态`}
          </Text>
        </div>
      </div>

      <div id="scrollableDiv" className={styles.scrollContent}>
        <InfiniteScroll
          dataLength={data.length}
          next={() => loadData(false)}
          hasMore={hasMore}
          loader={
            <div className={styles.loadingWrapper}>
              <Spin />
            </div>
          }
          endMessage={
            <div className={styles.endMessage}>
              {data.length > 0 ? '没有更多了' : '暂无动态'}
            </div>
          }
          scrollableTarget="scrollableDiv"
        >
          {data.map((item) => (
            <Card
              key={item.id}
              className={styles.dynamicCard}
              bordered={false}
              onClick={() => handleDynamicClick(item.id!)}
            >
              <div className={styles.dynamicContent}>
                <h3 className={styles.title}>{item.title}</h3>
                <div className={styles.time}>
                  <CalendarOutlined /> {formatDate(item.date)}
                </div>
                <div className={styles.text}>{item.content}</div>
                {renderMediaGrid(item.imageList)}
              </div>
            </Card>
          ))}
        </InfiniteScroll>
      </div>
    </div>
  );
};

export default DynamicPage; 